package com.hqd.jjvm.classformat.attributeinfo;

import com.hqd.jjvm.classformat.ClassFile;
import com.hqd.jjvm.util.HexStrTransformUtil;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Getter
@NoArgsConstructor
public class StackMapTable extends AttributeInfo {
	private Integer numberOfEntries;

	public StackMapTable(Integer attributeNameIndex, Integer attributeLength, Integer numberOfEntries) {
		super(attributeNameIndex, attributeLength);
		this.numberOfEntries = numberOfEntries;
	}

	@Override
	protected StackMapTable newAttributeInfo(Integer attributeNameIndex, Integer attributeLength, ClassFile classFile) {
		this.numberOfEntries = HexStrTransformUtil.parseHexToInt(classFile.readU2());
		for (int i = 0; i < numberOfEntries; i++) {
			int stackMapType = HexStrTransformUtil.parseHexToInt(classFile.readU1());
			if (stackMapType >= 0 && stackMapType <= 63) {
			} else if (stackMapType >= 64 && stackMapType <= 127) {
				verificationTypeInfo(classFile);
			} else if (stackMapType == 247) {
				int offetDelta = HexStrTransformUtil.parseHexToInt(classFile.readU2());
				verificationTypeInfo(classFile);
			} else if (stackMapType >= 248 && stackMapType <= 250) {
				int offetDelta = HexStrTransformUtil.parseHexToInt(classFile.readU2());
			} else if (stackMapType == 251) {
				int offetDelta = HexStrTransformUtil.parseHexToInt(classFile.readU2());
			} else if (stackMapType >= 252 && stackMapType <= 254) {
				int offetDelta = HexStrTransformUtil.parseHexToInt(classFile.readU2());
				for (int j = 0; j < stackMapType - 251; j++) {
					verificationTypeInfo(classFile);
				}
			} else if (stackMapType == 255) {
				int offetDelta = HexStrTransformUtil.parseHexToInt(classFile.readU2());
				int numberOfLocals = HexStrTransformUtil.parseHexToInt(classFile.readU2());
				for (int j = 0; j < numberOfLocals; j++) {
					verificationTypeInfo(classFile);
				}
				int numberOfStackItems = HexStrTransformUtil.parseHexToInt(classFile.readU2());
				for (int j = 0; j < numberOfStackItems; j++) {
					verificationTypeInfo(classFile);
				}
			}
		}
		return this;
	}

	/**
	 * 检测StackMapTable
	 *
	 * @return
	 */
	private void verificationTypeInfo(ClassFile classFile) {
		int tag = HexStrTransformUtil.parseHexToInt(classFile.readU1());
		if (tag >= 7) {
			classFile.readU2();
		}
	}
}
